//
//  BkShareAlertViewController.m
//  TuDianEducation
//
//  Created by lixinkeji on 2021/2/5.
//  Copyright © 2021 zhangbenchao. All rights reserved.
//

#import "BkShareAlertViewController.h"

@interface BkShareAlertViewController ()
@property (nonatomic, strong) UIView *bacView;

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic,strong) UIImageView *lessionImg;
@property (nonatomic, strong) UILabel *goodsNameLabel;
@property (nonatomic,strong) UILabel *priceLabel;
@property (nonatomic,strong) UILabel *hightPriceLabel;
@property (nonatomic,strong) UIImageView *qrImgView;
@property (nonatomic, strong) UIButton *commitBtn;



@end

@implementation BkShareAlertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.view.backgroundColor = kBacColor;
   
    [self.view addSubview:self.bacView];
    [self.bacView addSubview:self.titleLabel];
    [self.bacView addSubview:self.lessionImg];
    [self.bacView addSubview:self.goodsNameLabel];
    [self.bacView addSubview:self.priceLabel];
    [self.bacView addSubview:self.hightPriceLabel];
    [self.bacView addSubview:self.qrImgView];
    [self.bacView addSubview:self.commitBtn];
    
    self.dataDic = _dataDic;
    [self userInforRequstAction];
    UITapGestureRecognizer *dissmiss = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dissMissAction)];
    self.view.userInteractionEnabled = YES;
    [self.view addGestureRecognizer:dissmiss];
}
-(UIView *)bacView{
    if (!_bacView) {
        _bacView = [[UIView alloc]initWithFrame:CGRectMake(TSScaleW(57), 0, TSScaleW(260), TSScaleW(470))];
        _bacView.centerY = TSScreenHeight/2.f;
        [_bacView setCornerRadius:TSScaleW(5)];
        _bacView.backgroundColor = kWhiteColor;
        UITapGestureRecognizer *dissmiss = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backViewAction)];
        _bacView.userInteractionEnabled = YES;
        [_bacView addGestureRecognizer:dissmiss];
    }
    return _bacView;
}
-(void)backViewAction
{
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //self.navigationController.navigationBarHidden = YES;
}

-(UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [TSWLTools allocLabel:@"分享一个好物给你，请查收" font:systemFont(TSScaleW(12)) textColor:kGrayTxtColor frame:CGRectMake(TSScaleW(40), TSScaleW(20), TSScaleW(178), TSScaleW(30)) textAlignment:(NSTextAlignmentCenter)];
        _titleLabel.backgroundColor = UIColorFromARGB(0xF1F1F1, 1);
        _titleLabel.cornerRadius = _titleLabel.height/2.f;
        
    }
    return _titleLabel;
}

-(UIImageView *)lessionImg
{
    if (!_lessionImg) {
        _lessionImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, TSScaleW(5) + _titleLabel.bottom, _bacView.width, TSScaleW(150))];
        _lessionImg.backgroundColor = kGrayTxtColor;
    }
    return _lessionImg;
}

-(UILabel *)goodsNameLabel{
    if (!_goodsNameLabel) {
        _goodsNameLabel = [TSWLTools allocLabel:@"初中数学运算大法" font:systemFont(TSScaleW(16)) textColor:kWhiteColor  frame:CGRectMake(TSScaleW(0), _lessionImg.bottom, _bacView.width, TSScaleW(35)) textAlignment:(NSTextAlignmentCenter)];
        _goodsNameLabel.backgroundColor = kGreenColor;
        
        
    }
    return _goodsNameLabel;
}
-(UILabel *)priceLabel{
    if (!_priceLabel) {
        _priceLabel = [TSWLTools allocLabel:@"￥0.00" font:systemFont(TSScaleW(12)) textColor:kRedColor frame:CGRectMake(TSScaleW(12), TSScaleW(15) + _goodsNameLabel.bottom, TSScaleW(200), TSScaleW(18)) textAlignment:(NSTextAlignmentLeft)];
        
    }
    return _priceLabel;
}

-(UILabel *)hightPriceLabel{
    if (!_hightPriceLabel) {
        _hightPriceLabel = [TSWLTools allocLabel:@"原价：￥0.00" font:systemFont(TSScaleW(12)) textColor:kGrayTxtColor frame:CGRectMake(TSScaleW(12), TSScaleW(8) + _priceLabel.bottom, TSScaleW(200), TSScaleW(12)) textAlignment:(NSTextAlignmentLeft)];
        
    }
    return _hightPriceLabel;
}
-(UIImageView *)qrImgView{
    if (!_qrImgView) {
        _qrImgView = [[UIImageView alloc]initWithFrame:CGRectMake(TSScaleW(90), TSScaleW(70) + _goodsNameLabel.bottom, TSScaleW(80), TSScaleW(80))];
        _qrImgView.backgroundColor = kGrayTxtColor;
    }
    return _qrImgView;
}
-(UIButton *)commitBtn{
    if (!_commitBtn) {
       _commitBtn = [TSWLTools allocButtonTitle:@"保存图片" font:systemBoldFont(14) textColor:kWhiteColor image:nil frame:CGRectMake(TSScaleW(83), TSScaleW(20) + _qrImgView.bottom, TSScaleW(95), TSScaleW(30)) sel:@selector(commitAction:) taget:self];
              _commitBtn.backgroundColor = kRedColor;
              [_commitBtn setCornerRadius:_commitBtn.height/2.f];
    }
    return _commitBtn;
}

-(void)commitAction:(UIButton *)sender
{
    [self save];
    !self.callBackBlcok?:self.callBackBlcok();

    
}
- (void)save {
    // 1.截图
    UIImage *image = [self captureWithView:self.bacView];

    // 2.保存到图片
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    [self dismissAction];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error)
    {
        
    }
    else
    {
        [MBProgressHUD showError:@"保存成功"];
    }
}
- (UIImage *)captureWithView:(UIView *)view
{
    // 1.开启上下文
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);

    // 2.将控制器view的layer渲染到上下文
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    // 3.取出图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    // 4.结束上下文
    UIGraphicsEndImageContext();

    return newImage;
}
-(void)dismissAction{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    NSString *oldprice = _dataDic[@"oldprice"];
    NSString *newprice = _dataDic[@"newprice"];
    
   NSArray *imgArray= _dataDic[@"images"];
    if (imgArray.count) {
        [_lessionImg sd_setImageWithURL:[NSURL URLWithString:imgArray.firstObject]];
    }
    
    _priceLabel.text = [NSString stringWithFormat:@"￥%.2f",newprice.doubleValue];
    
    NSString *string = _priceLabel.text;
    NSMutableAttributedString *atts = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range = [_priceLabel.text rangeOfString:@"."];
    range = NSMakeRange(1, range.location - 1);
    [atts setAttributes:@{ NSForegroundColorAttributeName:kRedColor,NSFontAttributeName:systemBoldFont(TSScaleW(20))} range:range];
    _priceLabel.attributedText = atts;
    _hightPriceLabel.text = [NSString stringWithFormat:@"原价：￥%.2f",oldprice.doubleValue];
    NSString *string2 = _hightPriceLabel.text;
    NSMutableAttributedString *atts2 = [[NSMutableAttributedString alloc] initWithString:string2];
    
    NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle],NSForegroundColorAttributeName:kGrayTxtColor,NSFontAttributeName:systemFont(TSScaleW(12))};
 
    range = NSMakeRange(0, string2.length);
        [atts2 setAttributes:attribtDic range:(NSMakeRange(0, _hightPriceLabel.text.length ))];

    
    _hightPriceLabel.attributedText = atts2;

    
    
    _goodsNameLabel.text = _dataDic[@"name"];
    
    
    
}
-(void)userInforRequstAction{
    if (kLogin) {
        [NetWorkTools postConJSONWithUrl:@"memberinfo" parameters:@{} success:^(id responseObject) {
            NSString *result = responseObject[@"result"];
            NSString *resultNote = responseObject[@"resultNote"];
            NSDictionary *data = responseObject[@"dataobject"];
            if ([result integerValue] == 0) {
                NSString *  invitationcode = data[@"invitationcode"];
               
                self.qrImgView.image = [self creatCIQRCodeImageWithString:[NSString stringWithFormat:@"http://app.daishengbook.com/h5/#/pages/detail/index?invitationcode=%@&gid=%@",invitationcode,self.dataDic[@"gid"]]];
            }else{
                 [MBProgressHUD showError:resultNote];
            }
                         
        } fail:^(NSError *error) {
            
        }];
    }
   
    
}
/**
 *  生成二维码
 */
- (UIImage *)creatCIQRCodeImageWithString:(NSString *)string
{
    // 1.创建过滤器，这里的@"CIQRCodeGenerator"是固定的
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复默认设置
    [filter setDefaults];
    // 3. 给过滤器添加数据
    NSString *dataString = string;
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    // 注意，这里的value必须是NSData类型
    [filter setValue:data forKeyPath:@"inputMessage"];
    // 4. 生成二维码
    CIImage *outputImage = [filter outputImage];
    // 5. 显示二维码
    // 该方法生成的图片较模糊
    //    self.codeImg.image = [UIImage imageWithCIImage:outputImage];
    // 使用该方法生成高清图
    return [self creatNonInterpolatedUIImageFormCIImage:outputImage withSize:self.qrImgView.width];
}

/**
 *  根据CIImage生成指定大小的UIImage
 *
 *  @param image CIImage
 *  @param size  图片宽度
 *
 *  @return 生成高清的UIImage
 */
- (UIImage *)creatNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1. 创建bitmap
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
    
}


@end
